<template>
    <div>
        <div class="main_operation">
            <div class="operation_left">
                <!-- <h3 class="title" style="min-width: 100px">历史曲线</h3> -->
            </div>
            <div class="operation_right">
                <a-select allowClear class="mr10" style="width: 200px" v-model="formList.equipment_id" @change="equipChange" placeholder="设备名称">
                    <a-select-option v-for="item in equipmentData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                </a-select>
                <a-select allowClear v-if="formList.equipment_id" class="mr10" style="width: 200px" v-model="formList.register_id" placeholder="设备数据">
                    <a-select-option v-for="item in itemDetail" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                </a-select>
                <a-select v-if="routerShow($route,'history_data_source')" allowClear class="mr10" style="width: 200px" v-model="formList.source_type" placeholder="数据来源">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option :value="0">频率</a-select-option>
                    <a-select-option :value="1">主动</a-select-option>
                    <a-select-option :value="2">下发</a-select-option>
                    <a-select-option :value="3">定时</a-select-option>
                </a-select>
                <a-range-picker style="width: 220px" class="mr5" @change="onDateChange" />
                <a-button class="mr10" type="primary" @click="onSearch">搜索</a-button>
                <a-button class="mr10" type="primary" @click="download">下载导出数据</a-button>
                <!-- <a-button type="primary" @click="downloadBtn">下载数据</a-button> -->
            </div>
        </div>
        <div class="main">
            <div ref="chartmainline" style="width:100%; height:300px;"></div>
            <a-table :pagination="false" :loading="tableLoad" :columns="Fields" :dataSource="dataLists.data" :rowKey="record => record.id" :scroll="{ y: 500 }">
            </a-table>
            <div class="pageBox">
                <a-pagination :total="dataLists.total" :showTotal="total => `共 ${total} 条数据`" :pageSize="dataLists.per_page || 1" :defaultCurrent="1" @change="pageChange" />
            </div>
        </div>
    </div>
</template>

<script>
import {
  mapState,
  mapActions,
} from 'vuex';

export default {
  name: 'History',
  data() {
    return {
      /* 通用模块 */
      // 列表
      tableLoad: false, // 列表loading状态
      formList: { // 列表信息
        page: 1,
        equipment_id: undefined,
        register_id: undefined,
      },
      /* 通用模块end */
      optionline: {
        title: {
          text: '历史曲线',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        legend: {
          data: ['历史曲线'],
        },
        xAxis: {
          data: [],
          name: '时间',
          inverse: false,
          // data: ["星期1", "星期2", "星期2", "星期4", "星期5", "星期6", "星期7"]
        },
        yAxis: {
          name: '属性值',
          scale: true,
        },
        series: [{
          // name: '历史数据',
          type: 'line', // 设置图表主题
          data: [],
          // data: [11, 55, 100, 111, 360, 200, 500]
        }],
      },
    };
  },
  mounted() {
    this.getLists(false); // 防止数据保留
    this.equipmentAll();
    this.drawLine();
    if (this.$route.query.equipmentId != undefined && this.$route.query.registerId != undefined) {
      this.formList = {
        equipment_id: Number(this.$route.query.equipmentId),
        register_id: Number(this.$route.query.registerId),
        page: 1,
      };
      this.registerDetail(this.$route.query.equipmentId);
      this.changeData();
    }
    // else if (this.$route.query.equipmentId != undefined) {
    //   this.formList = {
    //     equipment_id: Number(this.$route.query.equipmentId),
    //     page: 1,
    //   }
    //   this.registerDetail(this.$route.query.equipmentId)
    //   this.$notification.info({
    //     message: '设备数据需自行选择',
    //   });
    // }
  },
  computed: {
    ...mapState({
      Fields: state => state.dataCenterHistory.Fields,
      dataLists: state => state.dataCenterHistory.dataLists,
      requestCode: state => state.dataCenterHistory.requestCode,
      equipmentData: state => state.equipment.equipmentData,
      itemDetail: state => state.equiRegister.itemDetail,
    }),
  },
  watch: {
    dataLists() {
      this.drawLine();
    },
    equipmentData() {
      if (this.$route.query.equipmentId == undefined && this.$route.query.registerId == undefined) {
        this.formList.equipment_id = this.equipmentData[0].id;
        this.equipChange(this.equipmentData[0].id);
      }
    },
    itemDetail() {
      console.log(this.itemDetail);
      if (this.itemDetail.length > 0) {
        this.formList.register_id = this.itemDetail[0].id;
        this.changeData();
        console.log('设备change');
      } else {
        this.formList.register_id = undefined;
      }
    },
    // 'formList.equipment_id'() {
    //   console.log('设备change');
    //   this.autoSearch = false
    // },
    // autoSearch() {
    //   if (this.autoSearch) {
    //     this.changeData()
    //   }
    // }
  },
  methods: {
    /* 通用模块 */
    /* 接口 */
    ...mapActions({
      getLists: 'dataCenterHistory/getLists', // 列表
      equipmentAll: 'equipment/equipmentAll', // 所有设备名称
      registerDetail: 'equiRegister/registerDetail', // 所有设备寄存器信息
      exportData: 'dataCenterHistory/exportData', // 下载导出
    }),
    // 重新获取列表数据
    changeData() {
      this.tableLoad = true;
      this.getLists(this.formList);
      setTimeout(() => {
        // this.drawLine()
        this.tableLoad = false;
      }, 1000);
    },
    // 下载数据
    download() {
      console.log('点我下载');
      // 载
      this.exportData(this.formList).then((res) => {
        console.log(res);
        const execlName = '历史数据导出';
        if (res.data.type == 'application/json') {
				            this.$message.error('查询数据为空');
				        } else {
				            const blob = new Blob(
				                [res.data], {
				                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
				                },
          );
				            const aEle = document.createElement('a'); // 创建a标签
				            const href = window.URL.createObjectURL(blob); // 创建下载的链接
				            aEle.href = href;
				            aEle.download = execlName; // 下载后文件名
				            document.body.appendChild(aEle);
				            aEle.click(); // 点击下载
				            document.body.removeChild(aEle); // 下载完成移除元素
				            window.URL.revokeObjectURL(href); // 释放掉blob对象

				            this.$message.success('导出成功');
				        }
      });
    },
    // 时间选择
    onDateChange(date, dateStrings) {
      console.log(date, dateStrings);
      this.formList.created_start = dateStrings[0];
      this.formList.created_end = dateStrings[1];
      if (!date.length) {
        delete this.formList.created_start;
        delete this.formList.created_end;
      }
    },
    // 搜索
    onSearch() {
      this.changeData();
    },
    // 页码
    pageChange(page) {
      this.formList.page = page;
      this.changeData();
    },
    /* 通用模块end */

    drawLine() {
      // 基于准本好的DOM，初始化echarts实例
      const chartmainline = this.$echarts.init(this.$refs.chartmainline);
      // 绘制图表
      chartmainline.setOption(this.optionline);
      if (this.dataLists.length != 0) {
        chartmainline.setOption({
          xAxis: [{
            data: this.dataLists.chartData.date,
          }],
          series: {
            data: this.dataLists.chartData.value,
            label: {
              normal: {
                show: false,
              },
            },
          },
        });
      }
      window.onresize = () => {
        chartmainline.resize();
      };
    },
    // 设备名称变化
    equipChange(val) {
      // delete this.formList.register_id
      this.registerDetail(val);
    },
    downloadBtn() {
      alert('该功能正在开发中~~~');
    },
  },
  // watch: {
  // dataLists(newValue, oldValue) {
  //   this.drawLine()
  // }
  // },
};
</script>

<style scoped>

</style>
